<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/7/26
 * Time: 11:46
 */

namespace app\common\service\control;

use think\facade\Config;
use think\Db;
use app\common\service\{
    CommonService, FlugGasService, ControlService, InletFlueGasService
};

class ConcentrationRealService
{
    /**
     * 获取当前值的方案值、实际值、当前平均值趋势图
     * @author yy by 2019/7/26
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCurrentValue($param = [])
    {
        // 运行浓度
        $flugGasService     = new FlugGasService();
        $commonService      = new CommonService();
        $tsinghua_plan_name = Db::query("select name from control_plan_from_tsinghua_plan where plan_number = ? and confirm_scheme = 1", [$param['plan_number']])[0]['name'];//已确认的方案名称
        $response_time      = Db::query("select response_start_time,response_end_time,control_start_time,control_end_time from control_plan_name where plan_number = ?", [$param['plan_number']]);//管控时间
        $current_hour       = date('Y-m-d H', strtotime('-1 hour')) . ':00:00';
        $start_time         = $response_time[0]['control_start_time'];
        // 管控还没有开始
        if (time() < strtotime($response_time[0]['control_start_time'])) {
            $end_time       = $response_time[0]['control_end_time'];
            $data_all_hour  = $commonService->getDate($start_time, $end_time, $format = 'Y-m-d H');
            $future['date'] = $data_all_hour;
            $num_future     = count($data_all_hour);
            for ($i = 0; $i < $num_future; $i++) {
                $future['data'][0][$i] = '';
                $future['data'][1][$i] = '';
                $future['data'][2][$i] = '';
            }
            return $future;
        } else {
            $end_time = time() < strtotime($response_time[0]['control_end_time']) ? $current_hour : $response_time[0]['control_end_time'];
        }
        $tsingHua_emission        = $flugGasService->getQingHuaEmissionDrainDayAvg($param['plan_number'], $param['control_mode_id'], $tsinghua_plan_name, $param['company_id'], $param['drain_id'], strtoupper($param['type']));//清华预案小时排放量
        $tsingHua_emission_minute = $tsingHua_emission / 60;         // 清华分钟排放量
        // 模拟企业的运行浓度效率的方案值、实际值、当前平均值
        if ($param['company_id'] != 1) {
            $data_all_hour         = $commonService->getDate($start_time, $end_time, $format = 'Y-m-d H');
            $num_hour              = count($data_all_hour);
            $concentration['date'] = $data_all_hour;
            $efficiency['date']    = $data_all_hour;
            $simulate              = Db::query("select gas_volume, avg(operation_concentration_so2) as concentration_so2, avg(operation_concentration_nox) as concentration_nox, avg(operating_efficiency_so2) as efficiency_so2, avg(operating_efficiency_nox) as efficiency_nox 
                                    from company_industry_monitor_simulation_hour_avg where company_id  = ? and drain_id = ?", [$param['company_id'], $param['drain_id']]);
            for ($x = 0; $x < $num_hour; $x++) {
                // 模拟企业的运行浓度--方案值
                $concentration['data'][0][$x] = round($tsingHua_emission / $simulate[0]['gas_volume'], 1);
                // 模拟企业的运行浓度--实际值
                $concentration['data'][1][$x] = ($param['type'] == 'SO2') ? $simulate[0]['concentration_so2'] : $simulate[0]['concentration_nox'];
                // 模拟企业的运行浓度--当前平均值
                $concentration['data'][2][$x] = ($param['type'] == 'SO2') ? $simulate[0]['concentration_so2'] : $simulate[0]['concentration_nox'];

                // 模拟企业的运行效率--方案值
                if (strtoupper($param['type']) == 'SO2') {
                    $simulation_denominator = ($simulate[0]['efficiency_so2'] != 1) ? $tsingHua_emission_minute / (1 - $simulate[0]['efficiency_so2']) * 60 : ''; //分母
                } else {
                    $simulation_denominator = ($simulate[0]['efficiency_nox'] != 1) ? $tsingHua_emission_minute / (1 - $simulate[0]['efficiency_nox']) * 60 : ''; //分母
                }
                $efficiency['data'][0][$x] = ($simulation_denominator != 0) ? round(1 - $tsingHua_emission / $simulation_denominator, 1) : '';
                // 模拟企业的运行效率--实际值
                $efficiency['data'][1][$x] = ($param['type'] == 'SO2') ? $simulate[0]['efficiency_so2'] : $simulate[0]['efficiency_nox'];
                // 模拟企业的运行效率--当前平均值
                $efficiency['data'][2][$x] = ($param['type'] == 'SO2') ? $simulate[0]['efficiency_so2'] : $simulate[0]['efficiency_nox'];
            }
            if ($param['before_type'] == 1) {
                return $concentration;
            } else {
                return $efficiency;
            }
        }

        $mongodb_huanxin    = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $table              = strtoupper($param['type']) === 'SO2' ? 'company_industry_monitor_sulfur_minute' : 'company_industry_monitor_nitre_minute';
        $document           = [
            'aggregate'    => $table,
            'pipeline'     => [
                [
                    '$project' => [
                        'publish_time'           => 1,
                        'company_id'             => 1,
                        'inlet_flue_gas_volume'  => 1,//入口烟气量
                        'export_flue_gas_volume' => 1,//出口烟气量
                        'emissions'              => 1, //脱硫排放量
                        'emission'               => 1, //脱硝排放量
                        'time'                   => ['$substr' => ['$publish_time', 0, 13]],
                        'drain_id'               => 1,
                    ],
                ],
                [
                    '$match' => [
                        'company_id'   => (int)$param['company_id'],
                        'drain_id'     => (int)$param['drain_id'],
                        'publish_time' => [
                            '$gte' => $start_time,
                            '$lte' => $end_time,
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'             => '$time',
                        'emissions_total' => strtoupper($param['type']) === 'SO2' ? ['$sum' => '$emissions'] : ['$sum' => '$emission'],
                        'gas_total'       => strtoupper($param['type']) === 'SO2' ? ['$sum' => '$export_flue_gas_volume'] : ['$sum' => '$inlet_flue_gas_volume'],
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => false,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']);
        $concentration      = [
            'data' => [0 => [], 1 => [], 2 => []]
        ];
        if ($num > 0) {
            for ($i = 0; $i < $num; $i++) {
                $concentration['date'][$i] = $contribution_trend[0]['result'][$i]['_id'] . ':00:00';
                // 实际值
                $concentration['data'][1][$i] = $contribution_trend[0]['result'][$i]['gas_total'] > 0 ? round($contribution_trend[0]['result'][$i]['emissions_total'] / $contribution_trend[0]['result'][$i]['gas_total'], 1) : '';
            }
            // 当前平均值
            $average = array_sum($concentration['data'][1]) / $num;
            for ($m = 0; $m < $num; $m++) {
                $concentration['data'][2][$m] = round($average, 1);
            }
        }

        // 实时企业排口小时烟气量
        $gas     = $flugGasService->monitorSulfurExitDrainSmokeHour($start_time, $end_time, $param['company_id'], $param['drain_id'], strtoupper($param['type']));
        $gas_num = count($gas);
        if ($gas_num > 0) {
            for ($n = 0; $n < $gas_num; $n++) {
                // 方案值
                $concentration['data'][0][] = $gas[$n]['s_emission'] > 0 ? round($tsingHua_emission / $gas[$n]['s_emission'], 1) : '';
            }
        }
        if ($param['before_type'] == 1) {
//            sort($concentration['data']);
            return $concentration;
        } else {
            // 运行效率
            $efficiency = $this->getEfficiencyReal($param, $start_time, $end_time, $table, $tsingHua_emission, $tsingHua_emission_minute);
            return $efficiency;
        }
    }

    /**
     * 获取运行效率的当前值的方案值、实际值、当前平均值趋势图
     * @author yy by 2019/7/27
     * @param array $param
     * @param       $start_time
     * @param       $end_time
     * @param       $table
     * @param       $tsingHua_emission_minute '清华预案分钟排放量'
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getEfficiencyReal($param = [], $start_time, $end_time, $table, $tsingHua_emission, $tsingHua_emission_minute)
    {
        $emission        = $param['type'] == 'SO2' ? 'emissions' : 'emission';
        $mongodb_huanxin = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $document        = [
            'aggregate'    => $table,
            'pipeline'     => [
                [
                    '$project' => [
                        '_id'                  => 1,
                        'publish_time'         => 1,
                        'company_id'           => 1,
                        'operating_efficiency' => 1,// 运行效率
                        $emission              => 1, //排放量
                        'time'                 => ['$substr' => ['$publish_time', 0, 13]],
                        'drain_id'             => 1,
                        'industry_id'          => 1,
                    ],
                ],
                [
                    '$match' => [
                        'company_id'           => (int)$param['company_id'],
                        'drain_id'             => (int)$param['drain_id'],
                        'operating_efficiency' => ['$ne' => 1],
                        'publish_time'         => [
                            '$gte' => $start_time,
                            '$lte' => $end_time,
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'              => '$time',
                        'emissions_total'  => ['$sum' => '$' . $emission], // 实际值运行效率的分子（每小时的排放量和）
                        'denominator'      => ['$sum' => ['$divide' => ['$' . $emission, ['$subtract' => [1, '$operating_efficiency']]]]], // 实际值运行效率的分母
                        'denominator_plan' => ['$sum' => ['$divide' => [$tsingHua_emission_minute, ['$subtract' => [1, '$operating_efficiency']]]]], //方案值运行效率的分母
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command         = new \MongoDB\Driver\Command($document);
        $rows            = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray(); //这里传回的是stdClass Object
        $result          = ((array)$rows[0])['result'];
        foreach ($result as $k => &$v) {
            $v = (array)$v;
        }
        $num  = count($result);
        $list = ['data' => [[], [], []]];
        if ($num > 0) {
            for ($i = 0; $i < $num; $i++) {
                $list['date'][$i] = $list['date'][$i] = $result[$i]['_id'] . ':00:00';
                // 实际值
                $list['data'][1][$i] = $result[$i]['denominator'] > 0 ? round(1 - $result[$i]['emissions_total'] / $result[$i]['denominator'], 4) : '';
            }
            // 当前平均值
            $average = array_sum($list['data'][1]) / $num;
            for ($m = 0; $m < $num; $m++) {
                $list['data'][2][$m] = round($average, 4);
            }
        }
        if ($num > 0) {
            for ($n = 0; $n < $num; $n++) {
                // 方案值
                $list['data'][0][$n] = $result[$n]['denominator_plan'] > 0 ? round(1 - $tsingHua_emission / $result[$n]['denominator_plan'], 4) : '';
            }
        }
        return $list;
    }
}